package com.yupi.yuaicodemother.core.parser;

import com.yupi.yuaicodemother.ai.model.MultiFileCodeResult;

import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * @Author: LZY
 * @CreateTime: 2025-10-07
 * @Description:
 * @Version: 1.0
 */

public class MultiFileCodeParser implements CodeParser<MultiFileCodeResult>{


    private static final Pattern HTML_CODE_PATTERN = Pattern.compile("```html\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);
    private static final Pattern CSS_CODE_PATTERN = Pattern.compile("```css\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);
    private static final Pattern JS_CODE_PATTERN = Pattern.compile("```(?:js|javascript)\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);

//    private static final Pattern HTML_CODE_PATTERN = Pattern.compile("```html\\s*\\n([\\s\\S]*?)\\n```", Pattern.CASE_INSENSITIVE);
//    private static final Pattern CSS_CODE_PATTERN = Pattern.compile("```css\\s*\\n([\\s\\S]*?)\\n```", Pattern.CASE_INSENSITIVE);
//    private static final Pattern JS_CODE_PATTERN = Pattern.compile("```(?:js|javascript)\\s*\\n([\\s\\S]*?)\\n```", Pattern.CASE_INSENSITIVE);
//    // 增强版正则表达式，处理更多变体
//    private static final Pattern HTML_CODE_PATTERN =
//            Pattern.compile("```\\s*html\\s*\\n([\\s\\S]*?)\\n\\s*```", Pattern.CASE_INSENSITIVE);
//
//    private static final Pattern CSS_CODE_PATTERN =
//            Pattern.compile("```\\s*css\\s*\\n([\\s\\S]*?)\\n\\s*```", Pattern.CASE_INSENSITIVE);
//
//    private static final Pattern JS_CODE_PATTERN =
//            Pattern.compile("```\\s*(?:js|javascript)\\s*\\n([\\s\\S]*?)\\n\\s*```", Pattern.CASE_INSENSITIVE);
//
    /**
     * 解析多文件代码（HTML + CSS + JS）
     */
    public  MultiFileCodeResult parseCode(String codeContent) {
        MultiFileCodeResult result = new MultiFileCodeResult();
        // 提取各类代码
        String htmlCode = extractCodeByPattern(codeContent, HTML_CODE_PATTERN);
        String cssCode = extractCodeByPattern(codeContent, CSS_CODE_PATTERN);
        String jsCode = extractCodeByPattern(codeContent, JS_CODE_PATTERN);
        // 设置HTML代码
        if (htmlCode != null && !htmlCode.trim().isEmpty()) {
            result.setHtmlCode(htmlCode.trim());
        }
        // 设置CSS代码
        if (cssCode != null && !cssCode.trim().isEmpty()) {
            result.setCssCode(cssCode.trim());
        }
        // 设置JS代码
        if (jsCode != null && !jsCode.trim().isEmpty()) {
            result.setJsCode(jsCode.trim());
        }
        return result;
    }

    /**
     * 根据正则模式提取代码
     *
     * @param content 原始内容
     * @param pattern 正则模式
     * @return 提取的代码
     */
    private static String extractCodeByPattern(String content, Pattern pattern) {
        Matcher matcher = pattern.matcher(content);
//        System.out.printf("content"+ content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }


}
